<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
           <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                    <el-row>
                        <!-- 用户名 -->
                        <el-col :span="5">
                            <el-form-item :label="$t('User.queryLabel.loginName')" :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.userName.val" class="queryItemStyle" clearable
                                        :placeholder="$t('User.queryLabel.placeholderLoginName')"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 姓名 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('User.queryLabel.name')" :label-width="queryformLabelWidth">
                                <el-input v-model.trim="formQueryCondition.name.val" class="queryItemStyle" clearable
                                        :placeholder="$t('User.queryLabel.placeholderName')"></el-input>
                            </el-form-item>
                        </el-col>
                        <!-- 角色 -->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('User.queryLabel.role')" :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.role.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="item.keyId" :key="item.keyId" :label="item.roleName" v-for="item in roles"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!--专区权限-->
                        <el-col :span="5" :offset="1">
                            <el-form-item :label="$t('User.queryLabel.SpecialAreaPowers')" :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.SpecialAreaPowers.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="drug.keyId" :key="drug.keyId" :label="drug.speAreaName"
                                        v-for="drug in speAreas"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- 是否可用 -->
                        <el-col :span="5">
                            <el-form-item :label="$t('User.queryLabel.isEnabled')"  :label-width="queryformLabelWidth">
                                <el-select v-model="formQueryCondition.isEnable.val" class="queryItemStyle">
                                    <el-option :label="$t('label.all')" value=""></el-option>
                                    <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText"
                                    v-for="drug in enables"></el-option>
                                    <!-- <el-option :label="$t('label.available')" value="Available" ></el-option>
                                    <el-option :label="$t('label.invalid')" value="Invalid"></el-option> -->
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- 列表上的按钮 -->
                    <el-row>
                        <el-col :span="24">
                            <div style="text-align:right">
                                <el-form-item>
                                    <!-- 新增 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'saveBtnText'}" type="primary" v-if="test('onNewBtn')" @click="onNew('saveBtnText')">{{ $t('btnText.newBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 重置 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'resetBtnText'}" type="primary" @click="onReset('form')">{{ $t('btnText.resetBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 导出 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'exportBtnText'}" type="primary" @click="exportMaterial('exportBtnText')" icon="el-icon-download" :loading="loading">{{ $t('btnText.exportBtnText') }}</el-button>
                                <!-- </el-form-item> -->
                                <!-- <el-form-item> -->
                                    <!-- 查询 -->
                                    <el-button v-permission="{menuCode: menuCode, resourceCode: 'queryBtnText'}" type="primary" @click="onQuery('queryBtnText')" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                                    <!--<el-button type="primary" @click="onQuery" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>-->
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="dataBox" ref="dataBox">

                <transition enter-active-class="animated zoomIn" leave-active-class="animated rotateOut">
                    <el-table v-if="isInit" ref="singleTable"
                                :data="tableData"
                                :height="tableHeight"
                                @sort-change="sortChange"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                        <el-table-column type="index"  width="50" fixed="left"
                                            :label="$t('table.xh')" align="center">
                        </el-table-column>
                        <el-table-column :label="$t('table.op')" fixed="left" min-width="350">
                            <template slot-scope="scope">
                                <!-- 专区授权按钮 -->
                                <el-button size="gv" icon="fa fa-edit"
                                :loading="loading" @click="speAreaAuthorize(scope.$index, scope.row,'puthorizedZone')"
                                v-permission="{menuCode: menuCode, resourceCode: 'puthorizedZone'}"
                                            >{{ $t('User.btnText.specialAreaAuthorizationBtnText') }}</el-button>
                                <!-- 站点授权按钮 -->
                                <el-button size="gv" icon="fa fa-edit"
                                :loading="loading" @click="siteAuthorize(scope.$index, scope.row,'siteAuthorize')"
                                v-permission="{menuCode: menuCode, resourceCode: 'siteAuthorize'}"
                                            >{{ $t('User.btnText.siteAuthorizationBtnText') }}</el-button>
                                <!-- 角色授权按钮 -->
                                <el-button size="gv" icon="fa fa-edit"
                                :loading="loading" @click="roleAuthorize(scope.$index, scope.row,'authorizeBtnText')" v-permission="{menuCode: menuCode, resourceCode: 'authorizeBtnText'}"
                                            >{{ $t('btnText.authorizationBtnText') }}</el-button>
                                <el-button size="gv" icon="el-icon-edit" :loading="loading"
                                @click="edit(scope.$index, scope.row,'editBtnText')"  v-permission="{menuCode: menuCode, resourceCode: 'editBtnText'}"
                                            >{{ $t('btnText.editBtnText') }}</el-button>
                                <!-- 恢复按钮 -->
                                <el-button size="gv" icon="el-icon-delete"
                                            v-permission="{menuCode:menuCode,resourceCode:'recoveryBtnText'}"
                                            type="danger" :loading="loading" @click="recovery(scope.$index, scope.row,'recoveryBtnText')" v-show="scope.row.isEnable=='Invalid'"
                                            >{{ $t('btnText.recoveryBtnText') }}</el-button>
                                <el-button size="gv" icon="el-icon-delete" v-if="scope.row.isEnable=='Invalid'" v-permission="{menuCode: menuCode, resourceCode: 'delBtnText'}"
                                            type="danger" :loading="loading" @click="deleteRow(scope.$index, scope.row, 'delBtnText')"
                                            >{{ $t('btnText.deleteBtnText') }}</el-button>
                                <el-button size="gv" icon="el-icon-delete" v-if="scope.row.isEnable=='Available'"  v-permission="{menuCode: menuCode, resourceCode: 'passBtnText'}"
                                            type="danger" :loading="loading" @click="logoffRow(scope.$index, scope.row, 'passBtnText')"
                                            >{{ $t('btnText.logoffBtnText') }}</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="keyId" min-width="110" fixed="left"
                                :label="$t('User.table.userCode')" sortable="custom" sort-by="keyId">
                        </el-table-column>
                        <el-table-column prop="userName" min-width="110" fixed="left"
                                :label="$t('User.table.loginName')" sortable="custom" sort-by="userName">
                        </el-table-column>
                        <el-table-column prop="name" min-width="110" fixed="left"
                                :label="$t('User.table.name')" sortable="custom" sort-by="name">
                        </el-table-column>

                        <el-table-column prop="userRoleList" min-width="220"  :formatter="formatter"
                                :label="$t('User.table.role')"  sort-by="userRoleList">
                        </el-table-column>
                        <el-table-column prop="userSpeAreaList" min-width="220" :formatter="formatter"
                                :label="$t('User.table.SpecialAreaPowers')"  sort-by="userSpeAreaList">
                        </el-table-column>

                        <el-table-column prop="email" min-width="180"
                                :label="$t('User.table.email')" sortable="custom" sort-by="email">
                        </el-table-column>
                        <el-table-column prop="phone" min-width="110"
                                :label="$t('User.table.phone')" sortable="custom" sort-by="phone">
                        </el-table-column>
                        <!-- <el-table-column prop="lastLoginDate" min-width="180"
                                :label="$t('User.table.lastLoginDate')" sortable="custom" sort-by="lastLoginDate">
                        </el-table-column> -->
                        <el-table-column prop="isEnableName" min-width="110" sortable="custom"
                        :label="$t('table.isEnabled')" sort-by="isEnable">
                        </el-table-column>

                        <el-table-column :label="$t('table.lastUpdatedBy')" min-width="120" sortable="custom" prop="modifier" sort-by="modifier">
                        </el-table-column>
                        <el-table-column :label="$t('table.lastUpdateTime')" min-width="180" sortable="custom" prop="lastUpdatedDate" sort-by="lastUpdatedDate">
                        </el-table-column>

                    </el-table>
                </transition>

            </div>
        </div>
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>

         <!--编辑对话框-->
        <transition enter-active-class="animated rotateIn" leave-active-class="animated rotateOut">
            <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowEditForm" top="5vh" :close-on-click-modal="false">
                <el-form :model="editForm" ref="editForm" size="mini"
                        :label-position="editFormPosition" status-icon=status-icon :rules="editRules">
                    <el-input v-model.trim="editForm.keyId"  v-show="false"></el-input>
                    <el-form-item :label="$t('User.editLabel.loginName')" :label-width="editformLabelWidth" prop="userName">
                        <el-input v-model.trim="editForm.userName" maxlength="20" :disabled="canEditCode"
                                :placeholder="$t('User.editLabel.placeholderLoginName')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('User.editLabel.name')"
                                :label-width="editformLabelWidth" prop="name">
                        <el-input v-model.trim="editForm.name" maxlength="50"
                                :placeholder="$t('User.editLabel.placeholderName')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('User.editLabel.pwd')"
                                :label-width="editformLabelWidth" prop="passWord">
                        <el-input v-model.trim="editForm.passWord" maxlength="200" type="password" :placeholder="$t('User.editLabel.placeholderPwd')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('User.editLabel.email')" :label-width="editformLabelWidth" prop="email">
                        <el-input v-model="editForm.email" maxlength="100"
                                :placeholder="$t('User.editLabel.placeholderEmail')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('User.editLabel.phone')" :label-width="editformLabelWidth" prop="phone">
                        <el-input v-model="editForm.phone" maxlength="100"
                                :placeholder="$t('User.editLabel.placeholderPhone')"></el-input>
                    </el-form-item>

                    <el-form-item :label="$t('label.isEnabled')" :label-width="editformLabelWidth">
                        <el-select v-model="editForm.isEnable">
                            <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button size="mini" @click="isShowEditForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                    <el-button size="mini" type="primary" @click="submitForm('editForm',currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
                </div>
            </el-dialog>
        </transition>

        <!-- 角色授权对话框 -->
        <el-dialog :title="$t('User.editLabel.placeholderRoles')" :visible.sync="isShowSelectForm" top="5vh" :close-on-click-modal="false">
            <el-form :label-width="editformLabelWidth"
                        :label-position="editFormPosition" status-icon=status-icon>
                <template>
                    <el-checkbox-group v-model="userRoles">
                        <el-checkbox v-for="role in roles" :label="role.keyId" :key="role.keyId">{{role.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </template>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowSelectForm = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="submitRoleAuthorize(currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

        <!-- 专区授权对话框 -->
        <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowSelectForm2" top="5vh" :close-on-click-modal="false">
            <el-form label="$t('User.editLabel.SpecialArea')" :label-width="editformLabelWidth" prop="loginName">
                <template>
                    <el-checkbox-group v-model="userSpeAreas">
                        <el-checkbox v-for="speArea in speAreas" :label="speArea.keyId" :key="speArea.keyId">{{speArea.speAreaName}}</el-checkbox>
                    </el-checkbox-group>
                </template>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowSelectForm2 = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="submitSpeAreaAuthorize(currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

        <!-- 站点授权对话框 -->
        <el-dialog :title="$t('label.dialogTitle')" :visible.sync="isShowSelectForm3" top="5vh" :close-on-click-modal="false">
            <el-form label="$t('User.editLabel.SpecialArea')" :label-width="editformLabelWidth" prop="loginName">
                <template>
                    <el-checkbox-group v-model="userSites">
                        <el-checkbox v-for="site in sites" :label="site.keyId" :key="site.keyId">{{site.siteName}}</el-checkbox>
                    </el-checkbox-group>
                </template>
            </el-form>
            <div slot="footer">
                <el-button size="mini" @click="isShowSelectForm3 = false" :loading="loading">{{ $t('btnText.cancelBtnText') }}</el-button>
                <el-button size="mini" type="primary" @click="submitSiteAuthorize(currentResCode)" :loading="loading">{{ $t('btnText.saveBtnText') }}</el-button>
            </div>
        </el-dialog>

  </div>


</template>

<script>

import comBaseVue from '../../baseViewModel';
import {isLettersNumbers,isPassword,validatePhone,validateEMail} from "../../../util/validator.js";

export default {
  mixins: [comBaseVue],
  name:'User',
  props: {
    menuCode: String
  },
  data () {

    return {
        isShowSelectForm:false,
        isShowSelectForm2:false,
        isShowSelectForm3:false,
        isInit:false,
        tableHeight:100,
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
        enables: [],
        modelName:"com.ispr.iptv.entity.sys.SysUser",
        // 查询条件
        formQueryCondition: {
            userName: {
                key: 'userName',
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            name: {
                key: 'name',
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            role: {
                key: 'userRoleList.role.keyId',
                op: '=', // 操作符
                val: '' // 查询的值
            },
            SpecialAreaPowers: {
                key: 'userSpeAreaList.speAreaId',
                op: '=', // 操作符
                val: '' // 查询的值
            },
            isEnable: {
                key: 'isEnable',
                op: '=', // 操作符
                val: 'Available'
            },
        },

        // 编辑面板绑定的对象
        editForm: {
            keyId: 0,
            version: 0,
            userName: "",
            name: "",
            passWord: "",
            phone:"",
            email: "",
            isEnable: "Available"
        },
        // 编辑面板的验证规则
        editRules: {
            userName: [{ required: true, message: this.$i18n.t('User.rules.loginName'), trigger: 'blur' },{validator:isLettersNumbers,trigger:'blur'}],
            name: [{ required: true, message: this.$i18n.t('User.rules.name'), trigger: 'blur' }],
            passWord: [{ required: true, message: this.$i18n.t('User.rules.pwd'), trigger: 'blur' },{validator:isPassword,trigger:'blur'}],
            phone: [{validator:validatePhone,trigger:'blur'}],
            email: [{validator:validateEMail,trigger:'blur'}]
        },
        userId: "",//授权操作的用户ID
        roles:[],//可授权的角色信息
        userRoles: [],//用户已授权的角色，用于回显
        speAreas:[],//可授权的专区
        userSpeAreas:[],//用户已授权的专区，用于回显
        sites:[],//可授权的专区
        userSites:[],//用户已授权的专区，用于回显
        checkList2: [],

    }
  },
  methods:{
      //格式化表格数据
      formatter:function(row, column, cellValue, index){
          if(cellValue!=null && cellValue!="" && cellValue.length>15){
              return cellValue.substr(0, 15)+"...";
          }
          return cellValue;
      },
      test:function(btnCode){
          return true;
        },
    // 新增
    onNew: function(rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.userName = "";
        this.editForm.name = "";
        this.editForm.passWord = "";
        this.editForm.email = "";
        this.editForm.phone = "";
        this.curCommand = "SaveNew";
        this.canEditCode = false;
    },

     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.userName.val = "";
        this.formQueryCondition.name.val = "";
        this.formQueryCondition.role.val = "";
        this.formQueryCondition.SpecialAreaPowers.val = "";
        this.formQueryCondition.isEnable.val = "Available";
    },

    // 为状态下拉框赋值
    findEnables: function() {
        this.findByTypeCode("10001",this.setEnables)
    },
    // 查询状态下拉框数据成功后的回调
    setEnables: function(isSuccess,json) {
        try{
            if (isSuccess) {
                this.enables = [];
                for (var i = 0; i < json.data.length; i++) {
                    this.enables.push(json.data[i]);
                }
            }
            else {
                this.$message.error(json.msg);
            }
        }
        catch(e){
            alert(e);
        }
    },

      // 专区授权按钮单击事件
    authorize2: function(index, row) {
        this.checkList2 = [],
        this.isShowSelectForm2 = true;
    },
    success2: function(){
        this.isShowSelectForm2 = false;
        this.$message({
                message: this.$i18n.t("User.editLabel.authorizationTip"),
                type: 'success'
        });
        this.queryTable();
    },

    ////////////////////////////////////////////////////////角色授权开始////////////////////////////////////////////////
    // 角色授权按钮单击事件
    roleAuthorize: function(index, row,rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.keyId = row.keyId;
        //this.checkList = [],
        this.isShowSelectForm = true;
        var _this = this;
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.UserRoleEntity",
                opKey: "UserRoles",
                params: [{"key":"userId","op":"=","val":row.keyId},{"key":"isEnable","op":"=","val":"Available"}],
                userInfo: this.getUserInfo()
            };
            //   let headersObj = {
            //     'Content-Type': 'application/json',
            //     'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
            //     'X-AOHO-UserId': this.getUserInfo().keyID
            //   };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            //获取用户已授权的角色，并选中
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.userRoles = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.userRoles.push(res.data.data[i].keyId);
                        }
                    } else {
                        this.$message.error(res.data.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    this.$message.error(error);
                });
    },

    //角色授权提交
    submitRoleAuthorize: function(rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var requestArgs = {
                commandCode: "SysUserRoleSave",
                className: this.modelName,
                commandArgs: "Default",
                commandBody: {"keyId":this.keyId, "roleList":this.userRoles},
                userInfo: this.getUserInfo()
            };
            let headersObj = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
                'X-AOHO-UserId': this.getUserInfo().keyID
              };
              if (this.isExistResourceCode(this)) {
                headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            var _this = this;
            this.axios.post('/api/execute',
                    requestArgs, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.isShowSelectForm = false;
                        _this.$message({message: _this.$i18n.t("message.successTip"),type: 'success'});
                        _this.onQuery();
                    } else {
                        _this.$message({ message: _this.$i18n.t("errorCode." + res.data.msg),type: 'warning'});
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message({message: _this.$i18n.t("errorCode." + "serverError"), type: 'warning' });
                });
    },
    ////////////////////////////////////////////////////////角色授权结束////////////////////////////////////////////////

    ////////////////////////////////////////////////////////专区授权开始////////////////////////////////////////////////
    // 专区授权按钮单击事件
    async speAreaAuthorize(index, row,rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.keyId = row.keyId;
        await this.setSpeArea();
        this.isShowSelectForm2 = true;
        var _this = this;
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.UserSpeAreaEntity",
                opKey: "UserSpeAreas",
                params: [
                    {"key":"userId","op":"=","val":row.keyId},
                    {"key":"isEnable","op":"=","val":"Available"}
                ],
                userInfo: this.getUserInfo()
            };
            // let headersObj = {
            //     'Content-Type': 'application/json',
            //     'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
            //     'X-AOHO-UserId': this.getUserInfo().keyID
            //   };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            //获取用户已授权的专区，并选中
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.userSpeAreas = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.userSpeAreas.push(res.data.data[i].keyId);
                        }
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
    },

    //专区授权提交
    submitSpeAreaAuthorize: function(rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var requestArgs = {
                commandCode: "userSpeAreaAuthorize",
                className: this.modelName,
                commandArgs: "Default",
                commandBody: {"keyId":this.keyId, "speAreaList":this.userSpeAreas},
                userInfo: this.getUserInfo()
            };
        //  let headersObj = {
        //         'Content-Type': 'application/json',
        //         'Authorization': 'Bearer ' + this.getUserInfo().tokenCode,
        //         'X-AOHO-UserId': this.getUserInfo().keyID
        //       };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            var _this = this;
            this.axios.post('/api/execute',
                    requestArgs, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.isShowSelectForm2 = false;
                        _this.$message({message: _this.$i18n.t("message.successTip"),type: 'success'});
                        _this.onQuery();
                    } else {
                        _this.$message({ message: _this.$i18n.t("errorCode." + res.data.msg),type: 'warning'});
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message({message: _this.$i18n.t("errorCode." + "serverError"), type: 'warning' });
                });
    },
    ////////////////////////////////////////////////////////专区授权结束////////////////////////////////////////////////

    ////////////////////////////////////////////////////////站点授权开始////////////////////////////////////////////////
    // 站点授权按钮单击事件
    async siteAuthorize(index, row,rescode) {
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        this.keyId = row.keyId;
        await this.setSite();
        this.isShowSelectForm3 = true;
        var _this = this;
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.UserSiteEntity",
                opKey: "UserSites",
                params: [
                    {"key":"userId","op":"=","val":row.keyId},
                    {"key":"isEnable","op":"=","val":"Available"}
                ],
                userInfo: this.getUserInfo()
            };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            //获取用户已授权的站点，并选中
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.userSites = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.userSites.push(res.data.data[i].keyId);
                        }
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
    },

    //站点授权提交
    submitSiteAuthorize: function(rescode){
        this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var requestArgs = {
                commandCode: "userSiteAuthorize",
                className: this.modelName,
                commandArgs: "Default",
                commandBody: {"keyId":this.keyId, "siteList":this.userSites},
                userInfo: this.getUserInfo()
            };
              if (this.isExistResourceCode(this)) {
                this.headersObj['X-AOHO-Resource'] = this.menuCode + ',' + this.currentResCode;
              };
            var _this = this;
            this.axios.post('/api/execute',
                    requestArgs, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.isShowSelectForm3 = false;
                        _this.$message({message: _this.$i18n.t("message.successTip"),type: 'success'});
                        _this.onQuery();
                    } else {
                        _this.$message({ message: _this.$i18n.t("errorCode." + res.data.msg),type: 'warning'});
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message({message: _this.$i18n.t("errorCode." + "serverError"), type: 'warning' });
                });
    },
    ////////////////////////////////////////////////////////站点授权结束////////////////////////////////////////////////

    // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
        if(isSuccess){
            //this.curCommand = "UpdateProc";
            this.curCommand = "PartialUpdateProc";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            //this.editForm = json;
            this.editForm.keyId = json.keyId;
            this.editForm.userName = json.userName;
            this.editForm.name = json.name;
            this.editForm.passWord = json.passWord;
            this.editForm.phone = json.phone;
            this.editForm.email = json.email;
            this.editForm.isEnable = json.isEnable;
            this.editForm.version = json.version;
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },

    //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck:function setEditFormCheck(){
        if(this.curCommand == "SaveNew"){
            this.editFormCheck = [{
                    key: 'userName',
                    op: '=', // 操作符
                    val: this.editForm.userName// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                }];
        }else if(this.curCommand == "PartialUpdateProc"){
            this.editFormCheck = [{
                    key: 'userName',
                    op: '=', // 操作符
                    val: this.editForm.userName// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                },{
                    key: 'keyId',
                    op: '<>', // 操作符
                    val: this.editForm.keyId
                }];
        }

    },
    //恢复按钮
    recovery: function(index, row,rescode) {
     this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmNormalMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version, isEnable: "Available" };
                    _this.loading = true;
                    _this.procCommand("RecoveryProc",
                            _this.modelName,
                            "default",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    //删除
    deleteRow: function(index, row,rescode){
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
        var _this = this;
        this.$confirm(this.$i18n.t("message.confirmDelMessage"),
            this.$i18n.t("message.confirmTitle"), {
            confirmButtonText: this.$i18n.t("message.yes"),
            cancelButtonText: this.$i18n.t("message.cancel"),
            type: "warning",
            callback: function (action, instance) {
                if (action == "confirm") {
                    var commandBody = {  "keyId": row.keyId, "version": row.version };
                    _this.loading = true;
                    _this.procCommand("DelUserProc",
                            _this.modelName,
                            "default",
                            commandBody,
                            null,
                            _this.submitFormCallback);
                }

            }
        });
    },

    exportMaterial:function exportMaterial (rescode) {
      this.currentResCode = (rescode && rescode!=='') ? rescode : '';
      let param = { 'className': 'com.ispr.iptv.entity.sys.SysUser', 'opKey': 'Export', 'params': this.queryObjToArray(this.formQueryCondition), 'sort': [{ 'col': 'keyId', 'order': 'desc' }], 'fileName': '调配资材' };
      let fileName = '系统用户信息' + '.xlsx';
      this.downloadByIdOrName(this, '/file/export', 'param', JSON.stringify(param), fileName);
    },

    //加载可授权的角色信息
    setRole: function(index, row) {
        var _this = this;
        var queryRequest = {
                className: "com.ispr.iptv.entity.sys.SysRole",
                opKey: "Roles",
                params: [{"key":"isEnable","op":"=","val":"Available"}],
                userInfo: this.getUserInfo()
            };
            //查询可以授权的所有角色信息
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.roles = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.roles.push(res.data.data[i]);
                        }
                    } else {
                        _this.$message.error(res.msg);
                    }
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
    },
    //加载可授权的专区信息
    setSpeArea: function(index, row) {
        var _this = this;
        var queryRequest = {
            className: "com.ispr.iptv.entity.sys.SpeArea",
            opKey: "SpeArea",
            params: [{"key":"isEnable","op":"=","val":"Available"}],
            userInfo: this.getUserInfo()
        };
        //查询可以授权的所有角色信息
        return new Promise((resolve, reject)=>{
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.speAreas = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.speAreas.push(res.data.data[i]);
                        }
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                    resolve(_this.speAreas);
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
        });

            // this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
            //     .then(function(res) {
            //         if (res.data.code == "SUCCESS") {
            //             _this.speAreas = [];
            //             for (var i = 0; i < res.data.data.length; i++) {
            //                 _this.speAreas.push(res.data.data[i]);
            //             }
            //         } else {
            //             _this.$message.error(_this.$i18n.t("errorCode." + json.reason,json.message));
            //         }
            //     })
            //     .catch(function(error) {
            //         console.log(error);
            //         _this.$message.error(_this.$i18n.t("errorCode." + json.reason,json.message));
            //     });
    },

    //加载可授权的站点信息
    setSite: function(index, row) {
        var _this = this;
        var queryRequest = {
            className: "com.ispr.iptv.entity.sys.Site",
            opKey: "Site",
            params: [{"key":"isEnable","op":"=","val":"Available"}],
            userInfo: this.getUserInfo()
        };
        //查询可以授权的所有角色信息
        return new Promise((resolve, reject)=>{
            this.axios.post('/api/query', queryRequest, {headers: this.headersObj})
                .then(function(res) {
                    if (res.data.code == "SUCCESS") {
                        _this.sites = [];
                        for (var i = 0; i < res.data.data.length; i++) {
                            _this.sites.push(res.data.data[i]);
                        }
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                    resolve(_this.sites);
                })
                .catch(function(error) {
                    console.log(error);
                    _this.$message.error(error);
                });
        });
    },
    enterDown(){
          var g=this
          if(g.isShowEditForm){
              g.submitForm('editForm',g.currentResCode)
          }else if(g.isShowSelectForm2){
              g.submitSpeAreaAuthorize(g.currentResCode)
          }else if(g.isShowSelectForm){
              g.submitRoleAuthorize(g.currentResCode)
          }else if(g.isShowSelectForm3){
              g.submitSiteAuthorize(g.currentResCode)
          }else if(!g.loading){
              g.onQuery()
          }
      }
  },
  mounted: function mounted() {
    this.findEnables();
    this.setRole();
    this.setSpeArea();
    this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    this.isInit = true;
    this.formQueryCondition.isEnable.val = "Available";
    this.onQuery();

  }
}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-checkbox{
      width: 120px;
      margin: 10px 0;
      margin-left: 30px;
}
</style>
